package com.lyc.iotdb.common.iot;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.lyc.iotdb.common.xss.SQLFilter;
import lombok.extern.slf4j.Slf4j;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * iotdb 工具
 *
 * @author kisang
 * @version 1.0
 * @date 2023/11/23 15:43
 */
@Slf4j
public class IotdbUtil {

    /**
     * 查询sql语句拼接
     *
     * @param sql    基础sql语句
     * @param params 参数
     * @return 查询sql
     */
    public static String packingSql(String sql, Map<String, Object> params) {
        // 拼接查询条件
        Pattern r = Pattern.compile(IotdbConstant.PATTERN);
        Matcher m = r.matcher(sql);
        List<String> keyList = new ArrayList<>();
        while (m.find()) {
            keyList.add(m.group(1));
        }
        if (keyList.size() > 0) {
            for (String key : keyList) {
                Object val = params.get(key);
                if (ObjectUtil.isNotEmpty(val)) {
                    sql = sql.replaceAll("\\#\\{" + key + "\\}", "'" + StrUtil.toString(val) + "'");
                } else {
                    throw new IllegalArgumentException("param [" + key + "] is null");
                }
            }
        }

        // 检查排序参数
        if (ObjectUtil.isNotEmpty(params.get(IotdbConstant.ORDER_FIELD))) {
            String orderField = SQLFilter.sqlInject(StrUtil.toString(params.get(IotdbConstant.ORDER_FIELD)));
            String order = StrUtil.toString(params.get(IotdbConstant.ORDER));
            sql = sql + " ORDER BY " + orderField + " " + order;
        } else {
            // 默认按Time时间序列倒序
            sql = sql + " ORDER BY time DESC";
        }

//        // 拼接分页
//        // 默认当前页为1
//        int curPage = 1;
//        // 默认每页10条
//        int limit = 10;
//        if (ObjectUtil.isNotEmpty(params.get(IotdbConstant.PAGE))) {
//            curPage = Convert.toInt(params.get(IotdbConstant.PAGE));
//        }
//        if (ObjectUtil.isNotEmpty(params.get(IotdbConstant.LIMIT))) {
//            limit = Convert.toInt(params.get(IotdbConstant.LIMIT));
//        }
//        sql = sql + " LIMIT " + limit + " OFFSET " + (curPage - 1) * limit;
//        log.info("查询sql:{}", sql);
        return sql;
    }
}
